<?php

require_once("View/View/PageView.php");
require_once("Common/Model/commonThings.php");
require_once("WorkoutUpdates/View/WorkoutUpdateView.php");
require_once("WorkoutUpdates/Model/WorkoutUpdateModel.php");
require_once("login/src/Model/LoginValidation.php");

class WorkoutUpdatesController
{
	/**
	*@var PageView
	**/
	private $pageView;
	/**
	*@var WorkoutUpdateView
	**/
	private $workoutUpdateView;
	/**
	*@var WorkoutUpdateModel
	**/
	private $workoutUpdateModel;
	/**
	*@var Loginvalidation
	**/
	private $loginvalidation;

	public function __construct()
	{
		$this->pageView = new PageView();
		$this->workoutUpdateView = new WorkoutUpdateView();
		$this->workoutUpdateModel = new WorkoutUpdateModel();
		$this->loginvalidation = new LoginValidation();
	}
	

	/**
	*@return string
	**/
	public function getPage()
	{
		$this->workoutUpdateModel->resetMessages();
		if($this->workoutUpdateView->getIfAdded())
		{	
			$this->saveUpdate();
		}
		if($this->workoutUpdateView->getIfRemove())
		{
			$this->removeUpdate(); 
		}
		if($this->workoutUpdateView->getIfEdited())
		{
			$this->saveUpdate($this->workoutUpdateView->getIdToEdit()); 
		}

		$html = $this->workoutUpdateView->getWorkoutUpdatePage();
		$html = $this->pageView->getHtmlPage("Träningsuppdateringar - Träningsdagboken", "", $html);
		return $html;
	}

	/**
	*@param int
	**/
	private function saveUpdate($updateID = null)
	{
		if(commonThings::checkIfPost()) 
		{
			$title = $this->workoutUpdateView->getWorkoutUpdateTitle();
			$comment = $this->workoutUpdateView->getWorkoutUpdateComment();
			$workoutID = $this->workoutUpdateView->getWorkoutID();
			
			if($this->workoutUpdateModel->ValidateWorkoutUpdate($title, $comment, $workoutID, $updateID))
			{
				if($updateID === null)
				{	
					$this->workoutUpdateModel->createAndSaveWorkoutUpdate($title, $comment, $workoutID);
				}
				else
				{
					$this->workoutUpdateModel->createAndSaveWorkoutUpdate($title, $comment, $workoutID, $updateID); 
				}
			}
		}
	}


	private function removeUpdate()
	{
		$workoutID = $this->workoutUpdateView->getIdToRemove();
		$this->workoutUpdateModel->ValidateAndDeleteUpdate($workoutID);
		header("Location:WorkoutUpdates.php");

	}


	/**
	*@return bool 
	**/
	public function areWeLoggedIn()
	{
		if(!$this->loginvalidation->CheckIfWereLoggedIn())
		{
			header("Location:index.php");
		}
		return true;
	}


	
}